# 爬取图片

import re
import requests
import time
import os


def get_url(url):
    # 重试机会
    global html_url
    for i in range(3):
        try:
            response = requests.get(url)
            if response.status_code == 200:   # 状态码
                response.encoding = "utf-8"  #设置编码
                text = response.text
                # 正则匹配图片地址
                html_url = re.findall(r'(?<=src=)[^"\s]+', text)
                # print(html_url)
                return response.text
            else:
                time.sleep(1)  # 请求失败则睡一秒再重试
        except:
            time.sleep(1)

def downloadpic():
    j = 1
    for i in html_url:
        # 拼接图片地址
        pic_url = "https://www.sanchuangedu.cn/" + str(i)
        try:
            if pic_url is not None:
                print(f"正在下载第{j}张图片")
                pic = requests.get(pic_url, timeout=7)
                os.chdir(os.getcwd())
                pic_file = open(str(i), 'wb')  # 二进制创建并写入文件
                pic_file.write(pic.content)
                pic_file.close()
                j += 1
            else:
                continue
        except BaseException:
            print('错误，当前图片无法下载')
            continue

get_url("https://www.sanchuangedu.cn/")
downloadpic()
